package cards.controller;

import cards.dao.CardActivityDao;
import cards.dao.UserDao;
import cards.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import cards.service.CardActivityService;
import cards.util.HostHolder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Controller
public class EditController {
    @Value("${path.upload}")
    private String uploadPath;
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private CardActivityService cardActivityService;
    @Autowired
    private HostHolder hostHolder;

    @RequestMapping(path = "edit/{id}", method = RequestMethod.GET)
    public String displaycardActivitiesByUser( @PathVariable String id, Model model) {
        User user = hostHolder.getUser();
        model.addAttribute("user", user);
        return "edit";
    }

    @RequestMapping(path="edit/{id}",method=RequestMethod.POST)
    public String edit(@PathVariable String id,@RequestParam("title") String title, @RequestParam("startTime") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                       @RequestParam("endTime") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
                       @RequestParam("collectionRule") String rule,
                       @RequestParam("probability1") float prob1, @RequestParam("probability2") float prob2, @RequestParam("probability3") float prob3,
                       @RequestParam("probability4") float prob4, @RequestParam("probability5") float prob5,
                       @RequestParam("publicityPicture") MultipartFile card0,
                       @RequestParam("cardPicture1")MultipartFile card1,
                       @RequestParam("cardPicture2")MultipartFile card2, @RequestParam("cardPicture3")MultipartFile card3,
                       @RequestParam("cardPicture4")MultipartFile card4, @RequestParam("cardPicture5")MultipartFile card5,
                       HttpServletRequest request, Model model) {
        User user = hostHolder.getUser();
        model.addAttribute("user", user);
        if (card1 == null || card2 == null || card3 == null|| card4== null|| card5 == null|| card0 == null) {
            model.addAttribute("error", "未添加所有图片");
            return "addCardActivity";
        }
        String fileName1 = card1.getOriginalFilename();
        String fileName2 = card1.getOriginalFilename();
        String fileName3 = card1.getOriginalFilename();
        String fileName4 = card1.getOriginalFilename();
        String fileName5 = card1.getOriginalFilename();
        String fileName0 = card1.getOriginalFilename();
        if (StringUtils.isBlank(fileName1)) {model.addAttribute("error", "图片1不能为空");return "addCardActivity";}
        if (StringUtils.isBlank(fileName2)) {model.addAttribute("error", "图片2不能为空");return "addCardActivity";}
        if (StringUtils.isBlank(fileName3)) {model.addAttribute("error", "图片3不能为空");return "addCardActivity";}
        if (StringUtils.isBlank(fileName4)) {model.addAttribute("error", "图片4不能为空");return "addCardActivity";}
        if (StringUtils.isBlank(fileName5)) {model.addAttribute("error", "图片5不能为空");return "addCardActivity";}
        if (StringUtils.isBlank(fileName0)) {model.addAttribute("error", "展示图片不能为空");return "addCardActivity";}

        String suffix1 = fileName1.substring(fileName1.lastIndexOf("."));
        if (StringUtils.isBlank(suffix1)) {model.addAttribute("error", "图片1格式不正确");return "addCardActivity";}
        String suffix2 = fileName1.substring(fileName1.lastIndexOf("."));
        if (StringUtils.isBlank(suffix2)) {model.addAttribute("error", "图片2格式不正确");return "addCardActivity";}
        String suffix3 = fileName1.substring(fileName1.lastIndexOf("."));
        if (StringUtils.isBlank(suffix3)) {model.addAttribute("error", "图片3格式不正确");return "addCardActivity";}
        String suffix4 = fileName1.substring(fileName1.lastIndexOf("."));
        if (StringUtils.isBlank(suffix4)) {model.addAttribute("error", "图片4格式不正确");return "addCardActivity";}
        String suffix5 = fileName1.substring(fileName1.lastIndexOf("."));
        if (StringUtils.isBlank(suffix5)) {model.addAttribute("error", "图片5格式不正确");return "addCardActivity";}
        String suffix0 = fileName1.substring(fileName1.lastIndexOf("."));
        if (StringUtils.isBlank(suffix0)) {model.addAttribute("error", "展示图片格式不正确");return "addCardActivity";}
        int status = 0;
        int participants =0;
        int fullCollectors = 0;
        Date createTime = new Date();
        int compare1 = startTime.compareTo(endTime);
        int compare2 = startTime.compareTo(createTime);
        int compare3 = createTime.compareTo(endTime);
        if(compare1 >= 0){model.addAttribute("error", "活动开始时间没有早于活动结束时间");return "addCardActivity";}
        if(compare2 <= 0 && compare3 < 0){status = 1;}//上架活动
        if(prob1 <= 0 ||prob1 <= 0 ||prob1 <= 0 ||prob1 <= 0 ||prob1 <= 0 ){model.addAttribute("error", "每项概率必须大于0");return "addCardActivity";}
        if(prob1 + prob2 + prob3 +prob4 +prob5 <= 0.99 || prob1 + prob2 + prob3 +prob4 +prob5 >= 1.01){
            model.addAttribute("error", "概率之和必须为1");
        }
        else
        {float prob = prob1 + prob2 + prob3 +prob4 +prob5;
            prob1 = prob1/prob;prob2 = prob2/prob;prob3 = prob3/prob;prob4 = prob4/prob;prob5 = prob5/prob; }

        // 生成随机文件名
        fileName1 =  UUID.randomUUID().toString().replaceAll("-", "") + suffix1;
        fileName2 =  UUID.randomUUID().toString().replaceAll("-", "") + suffix2;
        fileName3 =  UUID.randomUUID().toString().replaceAll("-", "") + suffix3;
        fileName4 =  UUID.randomUUID().toString().replaceAll("-", "") + suffix4;
        fileName5 =  UUID.randomUUID().toString().replaceAll("-", "") + suffix5;
        fileName0 =  UUID.randomUUID().toString().replaceAll("-", "") + suffix0;
        String path0 = uploadPath + "\\" + fileName0;
        String path1 = uploadPath + "\\" + fileName1;
        String path2 = uploadPath + "\\" + fileName2;
        String path3 = uploadPath + "\\" + fileName3;
        String path4 = uploadPath + "\\" + fileName4;
        String path5 = uploadPath + "\\" + fileName5;

        // 确定存放路径
        storeFileToDest(card0, path0);
        storeFileToDest(card1, path1);
        storeFileToDest(card2, path2);
        storeFileToDest(card3, path3);
        storeFileToDest(card4, path4);
        storeFileToDest(card5, path5);

        return cardActivityService.updateCardActivity(id, title,fileName0,startTime,endTime,suffix0,
                fileName1,fileName2,fileName3,fileName4,fileName5,rule,
                prob1,prob2,prob3,prob4,prob5,
                createTime,status,participants,fullCollectors);

    }
    private void storeFileToDest(MultipartFile card5, String path) {
        File dest5 = new File(path);
        try {card5.transferTo((dest5));
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getMessage());
            System.out.println("上传文件失败" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生异常");
        }
    }
}

